import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Link } from 'dva/router';
import { Button, Card, Modal } from 'antd';
import moment from 'moment';

import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import TableList from '../../components/TableList';
import DropdownMenu from '../../components/DropdownMenu';
import ModalView from './ModalView';

import styles from './ControllerPlugin.less';

const { confirm } = Modal;
const getValue = obj => Object.keys(obj).map(key => obj[key]).join(',');


@connect(state => ({
  controllerplugin: state.controllerplugin,
}))

export default class ControllerPlugin extends PureComponent {
  state = {
    modalVisible: false,
    modalCurrentItem: {},
    modalType: false, // F:create ; T:update
    selectedRows: [],
    formValues: {},
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'controllerplugin/fetch',
    });
  }
  handleModalOK = (data) => {
    const { dispatch } = this.props;
    const method = this.state.modalType ? 'update' : 'add';
    dispatch({
      type: `controllerplugin/${method}`,
      payload: data,
    });
    this.setState({
      modalVisible: false,
    });
  };


  handleModalVisible = (flag) => {
    this.setState({
      modalVisible: !!flag,
    });
  };
  handleModalType = (flag) => {
    this.setState({
      // F:create ; T:update
      modalType: flag,
    });
  };
  handleModalItem = (item) => {
    this.setState({
      modalCurrentItem: item || {},
    });
  };
  handleSelectRows = (rows) => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      page: pagination.current - 1,
      size: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }
    dispatch({
      type: 'controllerplugin/fetch',
      payload: params,
    });
  };

  handleBatchDelete = () => {
    const { selectedRows } = this.state;
    const ids = selectedRows.map(item => item.id);
    this.props.dispatch({
      type: 'controllerplugin/batchRemove',
      payload: ids,
    });
    this.setState({
      selectedRows: [],
    });
  };

  render() {
    const RESOURCE_URL = '/res/controllerPlugins/';
    const { modalVisible, selectedRows, modalType, modalCurrentItem } = this.state;
    const { controllerplugin: { loading: controllerpluginLoading, data }, dispatch } = this.props;

    const handleMenuClick = (record, e) => {
      if (e.key === 'update') {
        this.handleModalType(true);
        this.handleModalVisible(true);
        this.handleModalItem(record);
      } else if (e.key === 'delete') {
        confirm({
          title: '确认删除这个ControllerPlugin？',
          onOk() {
            dispatch({
              type: 'controllerplugin/delete',
              payload: record.id,
            });
          },
        });
      }
    };

    const columns = [
      {
        title: '名字',
        dataIndex: 'name',
        render: (val, record) => (<Link to={RESOURCE_URL + record.id}>{val}</Link>),
      },
      {
        title: 'UUID',
        dataIndex: 'id',
        width: '200px',

      },
      {
        title: '描述',
        dataIndex: 'description',
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        // sorter: true,
        render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
      },
      {
        title: '操作',
        width: '100px',
        render: (text, record) => {
          return (
            <DropdownMenu
              onMenuClick={e => handleMenuClick(record, e)}
              menuOptions={[{ key: 'update', name: 'Update' }, { key: 'delete', name: 'Delete' }]}
            />);
        },
      },
    ];

    const modalProps = {
      modalType,
      visible: modalVisible,
      onCancel: () => this.handleModalVisible(),
      onOk: this.handleModalOK,
      item: modalCurrentItem,
    };


    return (
      <PageHeaderLayout
        title="ControllerPlugins"
        content={
          <p>这是传说中的ControllerPlugin</p>
        }
      >
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListOperator}>
              <Button
                icon="plus"
                type="primary"
                onClick={() => {
                  this.handleModalType(false);
                  this.handleModalVisible(true);
                  this.handleModalItem();
                }}
              >
                新建
              </Button>
              {
                selectedRows.length > 0 && (
                <Button type="danger" onClick={this.handleBatchDelete}>批量删除</Button>
                )
              }
            </div>
            <TableList
              selectedRows={selectedRows}
              loading={controllerpluginLoading}
              data={data}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
              columns={columns}
            />
          </div>
        </Card>
        {modalVisible && <ModalView {...modalProps} />}
      </PageHeaderLayout>
    );
  }
}
